/*
 * =================================================================================================
 * ADOBE SYSTEMS INCORPORATED
 * Copyright 2006 Adobe Systems Incorporated
 * All Rights Reserved
 *
 * NOTICE:  Adobe permits you to use, modify, and distribute this file in accordance with the terms
 * of the Adobe license agreement accompanying it.
 * =================================================================================================
 */

/**
 * An OutputStream wrapper that counts the written bytes.
 * This is the ArkTS implementation of the Java CountOutputStream.
 */
export default class CountOutputStream {
    /** the decorated output stream */
    private out: ESObject;
    /** the byte counter */
    private bytesWritten: number = 0;

    /**
     * Constructor with providing the output stream to decorate.
     * @param out an OutputStream-like object
     */
    constructor(out: ESObject) {
        this.out = out;
    }

    /**
     * Counts the written bytes.
     * @param buf byte array to write
     * @param off offset in the array
     * @param len number of bytes to write
     */
    write(buf: Uint8Array | number, off?: number, len?: number): void {
        if (off !== undefined && len !== undefined) {
            this.out.write(buf, off, len);
            this.bytesWritten += len;
        } else {
            if (buf instanceof Uint8Array) {
                this.out.write(buf);
                this.bytesWritten += buf.length;
            } else if (typeof buf === 'number') {
                this.out.write(buf);
                this.bytesWritten++;
            }
        }
    }

    /**
     * @return the number of bytes written
     */
    getBytesWritten(): number {
        return this.bytesWritten;
    }
}